package org.anddev.andengine.extra;

import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.layer.Layer;
import org.anddev.andengine.entity.modifier.AlphaModifier;
import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.util.modifier.IModifier;

public class FadeLayer extends Layer {
	private Rectangle mScreenBlack;
	
	public FadeLayer() {
		this.mScreenBlack = new Rectangle(0, 0, Enviroment.getInstance().getScreenWidth(), Enviroment.getInstance().getScreenHeight());
		this.mScreenBlack.setColor(0f, 0f, 0f);
		attachChild(this.mScreenBlack);
		
		fadeOut();
	}
	
	public void show() {
		this.mScreenBlack.setAlpha(1.0f);
	}
	
	public void hide() {
		this.mScreenBlack.setAlpha(0.0f);
	}
	
	public void fadeOut() {
		registerUpdateHandler(new TimerHandler(0.1f, false, new ITimerCallback() {
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				FadeLayer.this.mScreenBlack.registerEntityModifier(
						new AlphaModifier(0.3f, 1f, 0f, new IEntityModifierListener() {
							@Override
							public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
								FadeLayer.this.hide();
								((ExtScene)Enviroment.getInstance().getScene()).startScene();
							}
						})
				);
			}
		}));
	}
	
	public void fadeIn() {
		registerUpdateHandler(new TimerHandler(0.1f, false, new ITimerCallback() {
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				FadeLayer.this.mScreenBlack.registerEntityModifier(
						new AlphaModifier(0.3f, 0f, 1f, new IEntityModifierListener() {
							@Override
							public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
								FadeLayer.this.show();
								((ExtScene)Enviroment.getInstance().getScene()).endScene();
							}
						})
				);
			}
		}));
	}
}